package com.syp.auth.service.validator.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.syp.auth.dao.po.UserEntity;
import com.syp.auth.dao.repository.UserRepository;
import com.syp.auth.domain.ValidateResult;
import com.syp.auth.export.common.GeneralAccessVo;
import com.syp.auth.export.common.GeneralUserVo;
import com.syp.auth.export.common.GorgeousParameters;
import com.syp.auth.service.validator.SigninErrorEnum;
import com.syp.auth.service.validator.SigninValidatorI;
import com.syp.auth.util.MD5Util;

@Service
public class SigninValidatorImpl implements SigninValidatorI {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	private UserRepository userRepository;

	@Override
	public ValidateResult validate(GeneralUserVo guser, GeneralAccessVo gaccess) {
		ValidateResult vr = new ValidateResult(true);

		SigninErrorEnum se = null;
		// 校验必录项
		if (StringUtils.isEmpty(guser.getUserCode())) {
			se = SigninErrorEnum.usernameMustNotEmpty;
		} else if (StringUtils.isEmpty(guser.getPassword())) {
			se = SigninErrorEnum.passwordMustNotEmpty;
		} else if (StringUtils.isEmpty(gaccess.getIvCode())) {
			se = SigninErrorEnum.ivcMustNotEmpty;
		} else if (StringUtils.isEmpty(gaccess.getSid())) {
			se = SigninErrorEnum.tokenMustNotEmpty;
		} else if (StringUtils.isEmpty(gaccess.getApp())) {
			se = SigninErrorEnum.appMustNotEmpty;
		} else {
			// 校验验证码有效性
			final String key = GorgeousParameters.IVC_PREFIX + gaccess.getSid();
			final String ivc = this.stringRedisTemplate.execute(new RedisCallback<String>() {
				@Override
				public String doInRedis(RedisConnection connection) throws DataAccessException {
					String value = stringRedisTemplate.opsForValue().get(key);
					return value;
				}
			});
			if (StringUtils.isEmpty(ivc)) {
				se = SigninErrorEnum.ivcExpired;
			} else if (!gaccess.getIvCode().equalsIgnoreCase(ivc)) {
				se = SigninErrorEnum.ivcUncheck;
			} else if (gaccess.getIvCode().equalsIgnoreCase(ivc)) {// 验证码配置通过即删除
				stringRedisTemplate.delete(key);
			}
			if (se == null) {
				UserEntity u = userRepository.signin(guser.getUserCode(), MD5Util.md5(guser.getPassword()));
				if (u == null) {
					se = SigninErrorEnum.usernameOrPasswordUncheck;
				}
			}
		}

		if (se != null) {
			vr.valid(false).ecode(se.getType().name()).emsg(se.getEmsg());
		}

		return vr;
	}

}
